package com.rtx.edi.system.menu.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rtx.common.ObjectUtils;
import com.rtx.edi.system.menu.service.MenuPermissionService;
import com.rtx.exception.RtxWmsException;
import com.rtx.model.emums.EnumDataType;
import com.rtx.model.po.entity.system.MenuPermission;
import com.rtx.model.po.entity.system.User;
import com.rtx.model.po.entity.system.UserPermission;
import com.rtx.model.po.service.MenuPermissionDAO;
import com.rtx.model.po.service.UserPermissionDAO;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class MenuPermissionServiceImpl implements MenuPermissionService{
	
	@Autowired
	MenuPermissionDAO menuPermissionDAO;
	
	@Autowired
	UserPermissionDAO userPermissionDAO;

	@Override
	public MenuPermission queryMenuPermissionById(Long id) {
		return menuPermissionDAO.getById(id);
	}

	@Override
	public Page<MenuPermission> queryMenuPermissionByPage(MenuPermission menuPermission) {
        // 分页查询
        Page<MenuPermission> page = new Page<>(menuPermission.getPageNum(), menuPermission.getPageSize());
        String name = menuPermission.getName();
        menuPermission.setName(null);
        // 对象带参数查询
        LambdaQueryWrapper<MenuPermission> wrapper = new LambdaQueryWrapper<>(menuPermission);
        // 模糊查询
        wrapper.like(org.springframework.util.StringUtils.hasLength(name), MenuPermission::getName, name);
        // 排序查询
        wrapper.orderByDesc(MenuPermission::getId);
        menuPermissionDAO.selectPage(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), page, wrapper);
		return page;
	}

	  /**
     * 新增数据
     *
     * @param menuPermission 实例对象
     * @return 实例对象
     */
    @Override
    public MenuPermission insertMenuPermission(MenuPermission menuPermission) {
    	menuPermissionDAO.insertMenuPermission(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), menuPermission);
        return menuPermission;
    }

    /**
     * 修改数据
     *
     * @param menuPermission 实例对象
     * @return 实例对象
     */
    @Override
    public MenuPermission updateMenuPermission(MenuPermission menuPermission) {
        if (menuPermission.getId() == null) {
            throw new RtxWmsException("更新数据主键不能为空");
        }
        DateTime date = DateUtil.date();
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(EnumDataType.USER.getValue());
        menuPermission.setUpdUser(user.getUsername());
        menuPermission.setUpdTime(date);
        menuPermissionDAO.updateMenuPermission(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(),menuPermission);
        return this.queryMenuPermissionById(menuPermission.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteMenuPermissionById(Long id) {
        LambdaQueryWrapper<MenuPermission> qw = Wrappers.lambdaQuery();
        qw.eq(MenuPermission::getParentId, id);
        List<MenuPermission> menuPermissions = menuPermissionDAO.selectMenuPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(),qw);

        if (ObjectUtils.isNotEmpty(menuPermissions)) {

            throw new RtxWmsException("存在下级菜单，删除失败");
        }
        return menuPermissionDAO.deleteMenuPermissionById(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(),id) > 0;
    }

    /**
     * 批量删除数据
     *
     * @param ids 主键集合
     * @return 删除是否成功
     */
    @Override
    public int batchDeleteMenuPermissionByIds(Long[] ids) {
        return menuPermissionDAO.batchDeleteMenuPermissionByIds(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), ids);
    }

    /**
     * 获取用户菜单权限表信息
     *
     * @param value
     * @param userId
     * @param userLanguage
     * @return
     * @throws Exception
     */
    @Override
    public List<MenuPermission> getUserPermissionMenuInfo(Long userId, String userLanguage) throws Exception {
    	LambdaQueryWrapper<UserPermission> upqw = Wrappers.lambdaQuery();
    	upqw.eq(UserPermission::getUserId, userId);
    	List<UserPermission> uplist = userPermissionDAO.selectUserPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), upqw);
    	List<MenuPermission> permissionDefines = new ArrayList<MenuPermission>();
    	for(UserPermission up:uplist) {
    		LambdaQueryWrapper<MenuPermission> mpqw = Wrappers.lambdaQuery();
    		mpqw.eq(MenuPermission::getId, up.getPermissionId());
    		permissionDefines.addAll(menuPermissionDAO.selectMenuPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), mpqw));
    	}
        // 梳理树状数据
        return getMenuPermissions(permissionDefines, EnumDataType.MENU_TYPE_USER.getValue());
    }

    @Override
    public int addSiblingMenu(MenuPermission menuPermission) {
        String name = menuPermission.getName();
        Long parentId = menuPermission.getParentId();
        if (parentId == null) {
            throw new RtxWmsException("添加同级菜单ID不能为空");
        }
        if (StrUtil.isBlank(menuPermission.getCode())) {
            throw new RtxWmsException("编号不能为空");
        }
        if (StrUtil.isBlank(name)) {
            throw new RtxWmsException("名称不能为空");
        }
        if (menuPermission.getType() == null) {
            throw new RtxWmsException("类型不能为空");
        }
        if (parentId != 0) {
            menuPermission.setLevelName(menuPermission.getLevelName() + "->" + name);
        }

        menuPermission.setVersion(1);
        menuPermission.setIsDeleted(0);
        DateTime date = DateUtil.date();
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(EnumDataType.USER.getValue());
        menuPermission.setInsUser(user.getUsername());
        menuPermission.setInsTime(date);
        return menuPermissionDAO.insertMenuPermission(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), menuPermission);
    }

    @NotNull
    private List<MenuPermission> getMenuPermissions(List<MenuPermission> permissionDefines, String menuType) {
        // 梳理树状数据
        List<MenuPermission> newPermissionDefines = findMenuPermissionTreePid(permissionDefines, menuType);
        // 1.8l拉姆达表达式删除
        newPermissionDefines.removeIf((MenuPermission) -> MenuPermission.getNodes() == null);
        return newPermissionDefines;
    }

    private List<MenuPermission> findMenuPermissionTreePid(List<MenuPermission> permissionDefines, String menuType) {

        List<MenuPermission> genList = new ArrayList<>();
        List<MenuPermission> childrenList = new ArrayList<>();

        for (MenuPermission tree : permissionDefines) {
            if (tree.getParentId() == 0) {
                genList.add(tree);
            } else {
                childrenList.add(tree);
            }
        }

        if (genList.size() > 0) {
            for (MenuPermission tree : genList) {
                dgMenuPermissionTree(tree, childrenList, menuType);
            }
        }
        return genList;
    }

    private void dgMenuPermissionTree(MenuPermission root, List<MenuPermission> rootList, String menuType) {

        List<MenuPermission> children = new ArrayList<>();
        List<MenuPermission> buttons = new ArrayList<>();

        for (MenuPermission tree : rootList) {

            // 是否子数据
            if (tree.getParentId().equals(root.getId())) {

                // 是否是子数据按钮
                if (ObjectUtil.equal(tree.getType(), Integer.valueOf(EnumDataType.MENU_TYPE_10102.getValue())) && ObjectUtil.equal(menuType, EnumDataType.MENU_TYPE_USER.getValue())) {

                    // 添加子数据按钮
                    buttons.add(tree);
                } else {

                    // 添加子数据
                    children.add(tree);
                }

                // 调用自己
                dgMenuPermissionTree(tree, rootList, menuType);
            }
        }

        // 添加子数据集合
        if (children.size() > 0) {
            root.setNodes(children);
        }

        // 添加子数据按钮集合
        if (buttons.size() > 0) {
            root.setButtons(buttons);
        }
    }

    /**
     * 菜单按钮维护列表
     *
     * @return
     */
    @Override
    public List<MenuPermission> lists() {
        List<MenuPermission> permissionDefines = menuPermissionDAO.selectMenuPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), Wrappers.lambdaQuery());
        return getMenuPermissions(permissionDefines, null);
    }
}
